const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const mongoose = require('mongoose');
const logger = require('./utils/logger');

// 加载环境变量
dotenv.config();

const app = express();

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 日志中间件
app.use((req, res, next) => {
  logger.info(`${req.method} ${req.path}`, { ip: req.ip });
  next();
});

// 连接数据库
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/i18n-platform', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
})
.then(() => logger.info('数据库连接成功'))
.catch(err => logger.error('数据库连接失败', err));

// 路由
app.use('/api/v1/products', require('./routes/products'));
app.use('/api/v1/translations', require('./routes/translations'));
app.use('/api/v1/releases', require('./routes/releases'));

// 健康检查
app.get('/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

// 错误处理
app.use((err, req, res, next) => {
  logger.error('服务器错误', err);
  res.status(err.status || 500).json({
    success: false,
    message: err.message || '服务器内部错误',
    ...(process.env.NODE_ENV === 'development' && { stack: err.stack })
  });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  logger.info(`国际化平台服务器运行在端口 ${PORT}`);
});

module.exports = app;

